package com.rxh.service.impl;


import com.rxh.mapper.core.CoreTradeRateMapper;
import com.rxh.mapper.sys.SysConstantMapper;
import com.rxh.pojo.core.CoreTradeRate;
import com.rxh.pojo.sys.SysConstant;
import com.rxh.service.TradeRateService;
import com.rxh.utils.SystemConstant;
import com.rxh.utils.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CacheConfig(cacheNames = "core_trade_rate")
@Service
public class TradeRateServiceImpl implements TradeRateService
{

	@Autowired
	private CoreTradeRateMapper tradeRateMapper;
	
	@Autowired
	private SysConstantMapper constantMapper;

	@CacheEvict(allEntries = true)
	@Override
	public Map<String, Object> save(CoreTradeRate entity) {


		Map<String, Object> map = new HashMap<String, Object>();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        entity.setCreateTime(timestamp);
        entity.setModifyTime(null);
        
        CoreTradeRate tradeRateObj = new CoreTradeRate();
        CoreTradeRate tradeRateParam = new CoreTradeRate();
        tradeRateParam.setSourceCurrency(entity.getSourceCurrency());
        tradeRateParam.setTargetCurrency(entity.getTargetCurrency());
        tradeRateParam.setType(entity.getType());
        tradeRateObj =  tradeRateMapper.selectByParam(tradeRateParam);
        int affectCount = 0 ;
        String msg = "";
        
        if(null == tradeRateObj){
        	
        	
        	affectCount = tradeRateMapper.insertSelective(entity);
        	   
        	
        }else {
        	
        	   msg = "此汇率已经存在，不能重复添加!";
        	
        }
        
		if(affectCount > 0){
			
			map.put("success", 1);
			
		}else{
			
			map.put("success", 0);
			map.put("msg",msg);
		}
		return map ;
		
	}

	@CacheEvict(allEntries = true)
	@Override
	public int deleteById(Long id) {
		
		return tradeRateMapper.deleteByPrimaryKey(id);
	}

	@CacheEvict(allEntries = true)
	@Override
	public int deleteByParam(Map<String, Object> param) {
		
		return tradeRateMapper.deleteByParam(param);
		
	}

	@CacheEvict(allEntries = true)
	@Override
	public Map<String, Object> update(CoreTradeRate entity) {
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Map<String, Object> map = new HashMap<String, Object>();
        BigDecimal newRate = entity.getRate();
    	String creator = entity.getCreator();
        String modifier = entity.getModifier();
        Date modifyTime = entity.getModifyTime();
        Date createTime = entity.getCreateTime();
        Short type = entity.getType();    //'0:交易汇率 1:结算汇率 2:划款汇率',
    	Date date = new Date();
    	String dataTime = sdf.format(createTime);
    	String currentTime = sdf.format(date);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());


        String msg = "";

        int affectCount = 0;
        
        if(dataTime.equals(currentTime)){
        	
        	entity.setModifyTime(timestamp);
        	affectCount = tradeRateMapper.updateByPrimaryKeySelective(entity);
        	
        	
        }else{
        	
        	//过去创建的日期的保存和新的产生
        	
        	entity.setCreateTime(null);
        	entity.setModifyTime(timestamp);
            entity.setStatus(SystemConstant.ENABLE);
            entity.setRate(0 != type ? entity.getRate() : null);
            affectCount = tradeRateMapper.updateByPrimaryKeySelective(entity);

            if(affectCount > 0 && 0 == type){  //只有类型为"交易汇率"时 才保存历史汇率
            	
            	entity.setCreateTime(date);
            	entity.setStatus(SystemConstant.DISABLE);
            	entity.setId(null);
            	entity.setCreator(entity.getModifier());
            	entity.setModifier(null);
            	entity.setModifyTime(null);
            	
            	CoreTradeRate tradeRateObj =  tradeRateMapper.selectByParam(entity);
            	
            	if(null == tradeRateObj){

                    entity.setCreateTime(createTime);
                    entity.setCreator(creator);
                    entity.setModifyTime(new Date());
                    entity.setModifier(modifier);
                    entity.setStatus(SystemConstant.ENABLE);
                    entity.setRate(newRate);
                    entity.setId(UUID.createKey("core_trade_rate"));
                	affectCount = tradeRateMapper.insertSelective(entity);
            		
            	}else{

            		msg = "此汇率已经存在，不能重复添加!";
            		affectCount = 0;
            		
            		
            	}
            	
            }
            
        }
		 
		if(affectCount > 0){
			
			map.put("success", 1);
			
		}else{
			
			map.put("success", 0);
			map.put("msg", msg);
			
		}
		return map ;
		
	}

	@CacheEvict(allEntries = true)
	@Override
	public int updateByIdSelective(CoreTradeRate entity) {
		// TODO Auto-generated method stub
		return tradeRateMapper.updateByPrimaryKeySelective(entity);
	}

	@Override
	public CoreTradeRate selectById(Long id) {
		// TODO Auto-generated method stub
		return tradeRateMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<CoreTradeRate> queryList(Map<String, Object> param) {
		// TODO Auto-generated method stub
		return tradeRateMapper.queryList(param);
	}

	@Override
	public Map<String, Object> getTradeRateInfo(Map<String, Object> paramMap) {

		Map<String, Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> searchInfoMap  = (Map<String,Object>) paramMap.get("searchInfo");
		if(null != searchInfoMap){
			
			paramMap.put("sourceCurrency", searchInfoMap.get("sourceCurrency"));
			paramMap.put("targetCurrency", searchInfoMap.get("targetCurrency"));
            paramMap.put("status", searchInfoMap.get("status")); //默认查询当前汇率
			paramMap.put("creator", searchInfoMap.get("creator"));
			paramMap.put("modifier", searchInfoMap.get("modifier"));
			paramMap.put("minCreateTime", searchInfoMap.get("minCreateTime"));
			paramMap.put("maxCreateTime", searchInfoMap.get("maxCreateTime"));
			paramMap.put("minModifyTime", searchInfoMap.get("minModifyTime"));
			paramMap.put("maxModifyTime", searchInfoMap.get("maxModifyTime"));
			paramMap.put("type", searchInfoMap.get("type"));
			
		}
        paramMap.put("status", "".equals(paramMap.get("status")) ? "0" :paramMap.get("status")); //默认查询当前汇率
        paramMap.put("merId", paramMap.get("merId"));
		paramMap.put("sortFieldName",paramMap.get("sortFieldName"));
		paramMap.put("sortType", paramMap.get("sortType"));

		Integer pageFirst = Integer.parseInt(paramMap.get("pageFirst")==null?"0":paramMap.get("pageFirst").toString());
		Integer pageSize = Integer.parseInt(paramMap.get("pageSize")==null?"10":paramMap.get("pageSize").toString());
		pageFirst = pageFirst * pageSize;
		paramMap.put("pageFirst", pageFirst);
		paramMap.put("pageSize", pageSize);

		List<CoreTradeRate> tradeList = tradeRateMapper.queryList(paramMap);

		int resultTotal = tradeRateMapper.getTradeAllResultCount(paramMap);

		resultMap.put("resultTotal", resultTotal);
		resultMap.put("tradeRateList", tradeList);
		resultMap.put("currency", constantMapper.selectByGroupNameAndSortValueIsNotNULL("Currency"));

		return resultMap;
		
	}

	@Override
	public Map<String, Object> getTradeRateInit() {
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		List<SysConstant> selectCurrencys = constantMapper.selectByGroupNameAndSortValueIsNotNULL("Currency");
		resultMap.put("selectCurrencys", selectCurrencys);
		return resultMap;
		
	}

	@CacheEvict(allEntries = true)
	@Override
	public Map<String, Object> deleteByParams(Map<String, Object> paramMap) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		int result = tradeRateMapper.deleteByParam(paramMap);
		if(result >= 1){
			
			map.put("result", "1");
			
		}else{
			
			map.put("result", "0");
		}
		
		return map;
	}

	@Cacheable(key = "'all'")
	@Override
	public List<CoreTradeRate> selectAll() {
		return tradeRateMapper.selectAll();
	}
}
